<template>
  <div id="video-block">
    <div
      id="video-button-container"
      @mouseover="hoverDanmu($event)"
      @mouseout="outDanmu($event)"
    >
      <video
        controls
        ref="video"
        id="player"
        @play="sendLocal"
        @pause="pausePlay"
      ></video>
      <div class="send-group">
        <div class="danmu-number">共计{{ danmuTotal }}条弹幕</div>
        <div class="open-danmu">
          <span>{{ isOpen ? "显示" : "隐藏" }}弹幕</span>
          <el-switch
            v-model="isOpen"
            @change="hiddenDanmu"
            active-color="#409EFF"
          >
          </el-switch>
        </div>
        <div class="danmu-speed">
          <span>弹幕速度</span>
          <el-slider v-model="speed" :min="1" :max="9"></el-slider>
        </div>
        <div class="danmu-speed danmu-opacity">
          <span>透明度</span>
          <el-slider
            v-model="opacity"
            :min="1"
            :max="10"
            @change="setOpacity"
          ></el-slider>
        </div>
        <div class="color-danmu">
          <span>弹幕颜色</span>
          <el-color-picker
            size="small"
            v-model="nowColor"
            :predefine="predefineColors"
          >
          </el-color-picker>
        </div>

        <el-input
          placeholder="请输入弹幕"
          v-model="danmuText"
          @keyup.enter.native="sendDanmu"
        >
          <el-button slot="append" @click="sendDanmu" style="color: #409eff"
            >发送</el-button
          >
        </el-input>
        <el-button @click="showNoteBlock" class="el-icon-edit write-note" plain
          >记笔记</el-button
        >
      </div>
    </div>
    <el-card :class="['note-container', { hidden: hiddenNote }]">
      <div slot="header" class="note-header">
        <span class="save-group">
          <el-tooltip effect="dark" content="点击保存" placement="left">
            <i class="el-icon-folder-checked to-save" @click="toSave"> </i>
          </el-tooltip>
          {{ tip }}</span
        >
        <i class="el-icon-close" @click="showNoteBlock"></i>
      </div>
      <div id="note-edit"></div>
    </el-card>
  </div>
</template>
<script>
import { getDanmu, setDanmu } from "@/services/danmu";
import { getNote, setNote } from "@/services/note";
import { getVedioById } from "@/services/course";
import E from "wangeditor";
export default {
  props: ["sectionId"],
  data() {
    return {
      videoUrl: "",
      vdoBlock: "",
      vdo: "",
      interKey: "",
      danmuList: [],
      danmuText: "",
      cleanDanmuInterKey: "",
      speed: 5,
      opacity: 7,
      nowColor: "#000000",
      danmuTotal: 0,
      isOpen: true,
      isPlay: false,
      predefineColors: [
        "#ff4500",
        "#ff8c00",
        "#ffd700",
        "#90ee90",
        "#00ced1",
        "#1e90ff",
        "#c71585",
        "#770881",
      ],
      hiddenNote: true,
      editor: "",
      note: "",
      tip: "内容加载中...",
      editKey: "",
      firstFlag: true,
      hoverKey: true,
      selectDanmu: "",
    };
  },
  methods: {
    initVideoPlayer() {
      getVedioById({ sectionId: this.sectionId }).then((res) => {
        this.$refs.video.src = res.data.msg;
      });
    },
    // 弹幕功能 =============================
    getDanmuBySectionId() {
      getDanmu({ sectionId: this.sectionId }).then((res) => {
        this.danmuList = res.data.danmuList;
        this.danmuTotal = this.danmuList.length;
      });
    },
    createDanmu(text, color, self = false) {
      let newDanmu = document.createElement("div");
      newDanmu.innerHTML = text;
      newDanmu.style.top = parseInt(Math.random() * 80) + "%";
      newDanmu.style.animationDuration = 10 - this.speed + "s";
      newDanmu.style.color = color;
      newDanmu.style.cursor = "pointer";
      newDanmu.style.opacity = this.opacity * 0.1;
      newDanmu.className = "danmu-item";
      if (!this.isOpen) {
        newDanmu.style.opacity = "0";
      }
      if (self) {
        newDanmu.style["border-bottom"] = "2px solid red";
      }
      this.vdoBlock.appendChild(newDanmu);
    },

    sendDanmu() {
      this.createDanmu(this.danmuText, this.nowColor, true);
      this.danmuTotal += 1;
      setDanmu(
        { sectionId: this.sectionId },
        {
          time: String(this.vdo.currentTime),
          text: this.danmuText,
          color: this.nowColor,
        }
      );
      // this.createDanmu(this.danmuText);
      this.danmuText = "";
      // alert(this.danmuText)
    },
    sendLocal() {
      this.isPlay = true;
      this.pauseDanmu("running");
      this.clearDanmu();

      this.interKey = setInterval(() => {
        // 弹幕列表为空则结束弹幕机
        if (this.danmuList.length == 0) {
          clearInterval(this.interKey);
          console.log("关闭了");
        }
        // 发送所有到达发送时间的弹幕
        while (this.danmuList[0].time <= this.vdo.currentTime) {
          this.createDanmu(
            this.danmuList[0].text,
            this.danmuList[0].color || "#333333"
          );
          this.danmuList.shift();
        }
        // console.log(this.vdo.currentTime)
      }, 50);
    },
    pauseDanmu(status) {
      let nodes = document.querySelectorAll(".danmu-item");
      for (let node of nodes) {
        node.style["animation-play-state"] = status;
      }
    },
    hiddenDanmu() {
      let nodes = document.querySelectorAll(".danmu-item");
      let status = this.isOpen ? this.opacity * 0.1 : "0";
      for (let node of nodes) {
        node.style.opacity = status;
      }
    },
    pausePlay() {
      this.isPlay = false;
      this.pauseDanmu("paused");
      clearInterval(this.cleanDanmuInterKey);
      clearInterval(this.interKey);
    },
    clearDanmu() {
      this.cleanDanmuInterKey = setInterval(() => {
        let nodes = document.querySelectorAll(".danmu-item");
        if (this.danmuList.length == 0 && nodes.length == 0) {
          clearInterval(this.cleanDanmuInterKey);
          console.log("结束清理");
        }
        for (let node of nodes) {
          if (parseInt(getComputedStyle(node).left) < 0) {
            this.vdoBlock.removeChild(node);
          }
        }
      }, 3000);
    },
    hoverDanmu(e) {
      if (!this.isPlay) {
        return;
      }
      if (this.hoverKey && e.target.className == "danmu-item") {
        this.hoverKey = false;
        this.selectDanmu = e.target;
        this.selectDanmu.style["z-index"] = "99999";
        this.selectDanmu.style["animation-play-state"] = "paused";
      }
    },
    outDanmu(e) {
      if (!this.isPlay) {
        return;
      }
      if (!this.hoverKey && e.target == this.selectDanmu) {
        this.selectDanmu.style["z-index"] = "1";
        this.selectDanmu.style["animation-play-state"] = "running";
        this.hoverKey = true;
      }
    },
    setOpacity() {
      let nodes = document.querySelectorAll(".danmu-item");
      for (let node of nodes) {
        node.style.opacity = this.opacity * 0.1;
      }
    },
    showNoteBlock() {
      this.hiddenNote = !this.hiddenNote;
    },
    initEditer() {
      const editor = new E("#note-edit");
      editor.config.onchange = (value) => {
        if (this.firstFlag) {
          this.firstFlag = false;
          return;
        }
        this.note = value;
        this.tip = "自动保存中...";
        clearTimeout(this.editKey);
        this.editKey = setTimeout(() => {
          this.sendNote(value);
        }, 5000);
      };
      editor.config.menus = $.map(editor.config.menus, function (item, key) {
        if (item === "video") {
          return null;
        }
        if (item === "emoticon") {
          return null;
        }
        if (item === "image") {
          return null;
        }
        return item;
      });
      editor.create();
      editor.txt.html("");
      this.editor = editor;
    },
    getMyNotes() {
      getNote({ sectionId: this.sectionId }).then((res) => {
        this.firstFlag = true;
        this.editor.txt.html(res.data.note);
        this.tip = "内容加载完成";
      });
    },
    toSave() {
      clearTimeout(this.editKey);
      this.sendNote(this.note, true);
    },
    sendNote(value, self = false) {
      setNote({ sectionId: this.sectionId }, { note: value }).then((res) => {
        var d = new Date();
        let str = "";
        str += d.getFullYear() + "年"; //获取当前年份
        str += d.getMonth() + 1 + "月"; //获取当前月份（0——11）
        str += d.getDate() + "日";
        str += d.getHours() + "时";
        str += d.getMinutes() + "分";
        str += d.getSeconds() + "秒";
        if (self) {
          this.tip = `保存成功 ${str}`;
        } else {
          this.tip = `自动保存成功 ${str}`;
        }
      });
    },
    getCurrentTime() {
      this.editor.txt.append(
        "<button @click='turnTime()' style='display: inline-block;background: #e6f4ff;color: #2392e5;font-weight: bold; border: 1px solid #e6f4ff;border-radius: 12px; height: 22px;line-height: 19px;user-select: none;padding: 0 10px;cursor: pointer;'>3:35</button>"
      );
      console.log(this.vdo.currentTime);
    },
    turnTime() {
      console.log(111);
    },
  },
  created() {
    this.initVideoPlayer();
    this.getDanmuBySectionId();
    this.getMyNotes();
  },
  mounted() {
    this.vdoBlock = document.getElementById("video-button-container");
    this.vdo = document.getElementById("player");
    this.initEditer();
  },
  watch: {
    sectionId: function () {
      this.initVideoPlayer();
      this.getDanmuBySectionId();
      this.getMyNotes();
      clearInterval(this.cleanDanmuInterKey);
      this.clearDanmu();
      // this.initEditer();
    },
  },
};
</script>
<style lang="scss">
#video-block {
  height: 100%;
  display: flex;
  #video-button-container {
    max-width: 100%;
    position: relative;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    #player {
      height: calc(100% - 50px);
    }
    .send-group {
      height: 45px;
      border-radius: 0 0 5px 5px;
      background-color: white;
      box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
      display: flex;
      justify-content: space-between;
      align-items: center;
      .danmu-number {
        font-size: 14px;
        color: gray;
        margin-left: 20px;
      }
      .open-danmu {
        font-size: 14px;
        color: gray;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 105px;
        margin-left: 30px;
      }
      .danmu-speed {
        font-size: 14px;
        color: gray;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 165px;
        margin-left: 25px;
        .el-slider {
          width: 100px;
          .el-slider__bar {
            background-color: #409eff;
          }
          .el-slider__button-wrapper {
            .el-slider__button {
              background-color: #409eff;
              border: 0;
            }
          }
        }
      }
      .danmu-opacity {
        width: 152px;
      }
      .color-danmu {
        font-size: 14px;
        color: gray;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 90px;
        margin-left: 30px;
        .el-color-picker__trigger {
          border: 0;
        }
      }
      .el-input {
        flex: 1;
        margin-right: 20px;
        //   margin-left: 5px;
        .el-input__inner {
          height: 30px;
          &:hover,
          &:focus {
            border-color: #409eff;
          }
        }
      }
      .write-note {
        background: #e6f4ff;
        color: #2392e5;
        border: 1px solid #e6f4ff;
        margin-right: 20px;
        height: 30px;
        padding: 0 10px;
      }
    }
    .danmu-item {
      position: absolute;
      color: gray;
      font-weight: bold;
      font-size: 20px;
      user-select: none;
      /* background-color: greenyellow; */
      top: 20px;
      right: 0%;
      transform: translate(100%, 0);
      white-space: nowrap;
      animation: danmuRun 5s linear forwards;
    }
    @keyframes danmuRun {
      from {
        right: 0%;
        transform: translate(100%, 0);
      }

      to {
        right: 100%;
        transform: translate(0, 0);
      }
    }
  }
  .note-container {
    width: 400px;
    height: calc(100% - 7px);
    margin-left: 10px;
    transition: 0.2s;
    position: relative;
    .note-header {
      display: flex;
      justify-content: space-between;
      position: relative;
      align-items: center;
      .save-group {
        display: flex;
        align-items: center;
        .to-save {
          color: #2392e5;
          font-size: 20px;
          margin-right: 5px;
          cursor: pointer;
        }
      }

      .el-icon-close {
        cursor: pointer;
      }
    }
    .el-card__body {
      padding: 0;
      position: absolute;
      height: calc(100% - 57px);
      #note-edit {
        height: 100%;
        display: flex;
        flex-direction: column;
        .w-e-menu[data-title="代码"] {
          .w-e-panel-container {
            width: 400px !important;
            margin-left: -347px !important;
          }
        }
        .w-e-text-container {
          flex: 1;
          .w-e-text {
            height: 100%;
            min-height: 400px !important;
            overflow-y: auto;
          }
        }
      }
    }
  }
  .hidden {
    width: 0;
    border: 0;
  }
}
</style>